import React, {useEffect, useState} from 'react';
import axios from 'axios'
import {Link} from "react-router-dom";
import LoadingSpinner from "../components/LoadingSpinner";
import InlineError from "../components/InlineError";
import EmptyResultsMessage from "../components/EmptyResultsMessage";
import * as errmsg from '../constants'


export default function Archives() {
    const [loading, setLoading] = useState(true);
    const [archives, setArchives] = useState([])
    const [error, setError] = useState('')

    useEffect(() => {
        axios.get('/api/v1/posts/get_archives/')
            .then(response => {
                setLoading(false)
                setArchives(response.data.results)
                setError('')
            })
            .catch(err => {
                setLoading(false)
                setArchives([])
                setError(errmsg.CUSTOM_ERROR_MSG)
            })
    }, [])

    const archiveList = (
        archives.map(archive => (
            <li key={archive.month}>
                <Link to={`/archive/${archive.year}/${archive.month}`} className="link-dark">
                    {archive.year}年{archive.month}月
                </Link>
                <small className="text-muted ms-2">
                    ({archive.post_count})
                </small>
            </li>
        ))
    )

    if (loading) return <LoadingSpinner/>
    if (error) return <InlineError error={error}/>
    if (archives.length === 0) return <EmptyResultsMessage/>

    return (
        <div className="px-4 mb-3">
            <h4 className="border-bottom mb-3">文章归档</h4>
            <ol className="list-unstyled mb-0">
                {archiveList}
            </ol>
        </div>
    )
};
